package com.tfswue.hql.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.tfswue.hql.entity.Book;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Update;
import org.apache.ibatis.annotations.Select;

import java.util.List;
import java.util.Map;

@Mapper
public interface BookMapper extends BaseMapper<Book> {

    /**
     * 减少图书可借数量
     */
    @Update("UPDATE book_hql SET available = available - 1 WHERE id = #{bookId} AND available > 0")
    int decreaseAvailable(@Param("bookId") Integer bookId);

    /**
     * 增加图书可借数量
     */
    @Update("UPDATE book_hql SET available = available + 1 WHERE id = #{bookId}")
    int increaseAvailable(@Param("bookId") Integer bookId);

    /**
     * 获取图书可借数量
     */
    @Select("SELECT available FROM book_hql WHERE id = #{bookId}")
    Integer getAvailableCount(@Param("bookId") Integer bookId);

    /**
     * 批量更新图书库存
     */
    @Update("UPDATE book_hql SET available = #{available}, stock = #{stock} WHERE id = #{bookId}")
    int updateBookStock(@Param("bookId") Integer bookId, 
                       @Param("available") Integer available, 
                       @Param("stock") Integer stock);

    /**
     * 获取热门图书统计
     */
    @Select("SELECT b.id, b.name, b.author, b.category, " +
            "COUNT(bb.id) as borrow_count, " +
            "b.stock - b.available as borrowed_count " +
            "FROM book_hql b " +
            "LEFT JOIN book_borrow bb ON b.id = bb.book_id " +
            "WHERE bb.borrow_date >= DATE_SUB(NOW(), INTERVAL 30 DAY) " +
            "GROUP BY b.id, b.name, b.author, b.category, b.stock, b.available " +
            "ORDER BY borrow_count DESC " +
            "LIMIT #{limit}")
    List<Map<String, Object>> getPopularBooks(@Param("limit") Integer limit);

    /**
     * 获取库存不足的图书
     */
    @Select("SELECT * FROM book_hql WHERE available <= #{threshold} ORDER BY available ASC")
    List<Book> getLowStockBooks(@Param("threshold") Integer threshold);

    /**
     * 按分类统计图书数量
     */
    @Select("SELECT category, COUNT(*) as count, " +
            "SUM(stock) as total_stock, " +
            "SUM(available) as available_stock " +
            "FROM book_hql " +
            "GROUP BY category " +
            "ORDER BY count DESC")
    List<Map<String, Object>> getBookStatsByCategory();

}

